package cn.tedu.charging.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将Java对象转换为JSON字符串
     * @param obj 要转换的Java对象
     * @return JSON字符串
     */
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
           e.printStackTrace();
        }
        return null;
    }

    /**
     * 将JSON字符串转换为Java对象
     *
     * @param jsonStr JSON字符串
     * @param clazz   目标Java对象的Class类型
     * @param <T>     泛型类型
     * @return 转换后的Java对象
     */
    public static <T> T fromJson(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert JSON to object", e);
        }
    }

}
